from nsga2.cnsga2 import CNSGA2
from problems.mw7 import MW7
import numpy as np
import matplotlib.pyplot as plt

def run_mw7():
    #-----------BEGIN-----------#
    #   1. Instantiate class CNSGA2() and class MW7()
    mw7 = MW7()
    cnsga2 = CNSGA2(pop_size=200, n_var=mw7.n_var)

    #   2. Use NSGA-II with a contraint handling technique to solve the MW7 problem
    population_x, optimum_fx = cnsga2.run(mw7, max_gen=200)

    #   3. Plot the final population `optimum_fx` in the objective space

    plt.figure(figsize=(5, 4))
    plt.scatter(optimum_fx[:, 0], optimum_fx[:, 1], c='gray', s=15,
                edgecolors='k', alpha=0.7)

    l = np.linspace(0, np.pi/2, 1000)

    # constraint 1
    r_min = np.maximum(1.0, 1.15 - 0.2 * (np.sin(4 * l))**8)
    # constraint 2
    r_max = 1.2 + 0.4 * (np.sin(4 * l))**16

    valid_mask = r_min < r_max
    l_valid = l[valid_mask]
    r_min_valid = r_min[valid_mask]
    r_max_valid = r_max[valid_mask]

    fill_f1 = np.concatenate([r_min_valid * np.cos(l_valid), r_max_valid[::-1] * np.cos(l_valid[::-1])])
    fill_f2 = np.concatenate([r_min_valid * np.sin(l_valid), r_max_valid[::-1] * np.sin(l_valid[::-1])])

    # feasible regions
    plt.fill(fill_f1, fill_f2, color='gray', alpha=0.2, edgecolor='none')

    plt.xlabel('f1', fontsize=12)
    plt.ylabel('f2', fontsize=12)
    plt.grid(True, alpha=0.3)
    plt.xlim(0, 1.5)
    plt.ylim(0, 1.5)
    plt.tight_layout()
    plt.show()
    #-----------END-----------#

if __name__ == "__main__":
    run_mw7()